<?php
namespace wechat;

use EasyWeChat\Factory;
use think\Exception;
use think\facade\Log;

class MsgSecCheck{
    /**
     * 微信文本内容安全识别
     * @author lichunguang
     * @since 2024/5/18 13:17
     * @param $appId
     * @param $appSecret
     * @param $openid
     * @param $content
     * @return true
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function checkText($appId, $appSecret, $openid, $content){
        //以下微信文本校验
        $config = [
            'app_id' => $appId,
            'secret' => $appSecret,
        ];
        $app          = Factory::miniProgram($config);
        $token        = $app->access_token->getToken();
        $access_token = $token['access_token'];
        $phoneDataRes = $app->access_token->request('https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' . $access_token, 'POST', [
            'json' => [
                "openid" => $openid,
                "scene" => 1,
                "version" => 2,
                'content' => $content,
            ]
        ]);
        $str = $phoneDataRes->getBody()->getContents();
        $checkResult    = json_decode($str, true);
        Log::info('check_text '. $str);
        if ($checkResult['errcode'] != 0) {
            throw new \Exception($checkResult["errmsg"]);
        }
        //
        $mapLabel = [100 => "正常", 10001 => "广告", 20001 => '时政', 20002 => '色情', 20003 => '辱骂', 20006 => '违法犯罪', 20008 => '欺诈', 20012 => '低俗', 20013 => '版权', 21000 => '其他'];
        $checkLabel = $checkResult["result"]["label"] ?? 0;
        if($checkLabel == 100){
            return true;
        }
        throw new \Exception("输入项涉及 ". $mapLabel[$checkLabel] ?? '');
    }
}